package com.zhuss.core.processor;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.zhuss.bean.bo.core.user.CreateUserBo;
import com.zhuss.common.AbstractBo;
import com.zhuss.common.ResponseSucc;
import com.zhuss.core.db.dao.ext.TempDao;
import com.zhuss.core.db.entity.Company;
import com.zhuss.core.db.entity.Role;
import com.zhuss.core.db.entity.Temp;
import com.zhuss.core.db.entity.User;
import com.zhuss.exception.ExceptionCode;
import com.zhuss.util.ExcelUtil;
import com.zhuss.util.NoUtil;
import com.zhuss.util.PingYinUtil;
import com.zhuss.util.UserUtil;

@Component("userImport")
public class UserImport {
	
	@Autowired
	@Qualifier("companyRead")
	private CompanyRead companyRead;
	
	@Autowired
	@Qualifier("userRead")
	private UserRead userRead;
	
	@Autowired
	@Qualifier("roleRead")
	private RoleRead roleRead;
	
	@Autowired
	private UserCreate userCreate;
	
	@Autowired
	private TempDao tempDao;
	

	public Object process(List<String[]> resultList, HttpServletResponse response) throws Exception {
		AbstractBo abstractBo = new AbstractBo();
		
		List<Temp> tempList = new ArrayList<Temp>();
		
		String batchNubmer = NoUtil.gen();
		Date now = new Date();
		Map<String, Integer> userTypeMap = UserUtil.getUserTypeMap();
		Map<String, Integer> sexMap = UserUtil.getSexMap();
		Map<String, Company> companyMap = companyRead.listMap();
		Map<String, Role> roleMap = roleRead.listMap();
		
		outer:
		for (int i = 0; i < resultList.size(); i ++) {
			if (i == 0) {
				continue;
			}
			String[] item = resultList.get(i);
			
			String item0 = item[0];
			String item1 = item[1];
			String item2 = item[2];
			String item3 = item[3];
			String item4 = item[4];
			String item5 = item[5];
			String item6 = item[6];
			String item7 = item[7];
			String item8 = item[8];
			
			
			Temp temp = new Temp();
			temp.setItem0(item0);
			temp.setItem1(item1);
			temp.setItem2(item2);
			temp.setItem3(item3);
			temp.setItem4(item4);
			temp.setItem5(item5);
			temp.setItem6(item6);
			temp.setItem7(item7);
			temp.setItem8(item8);
			temp.setAccount(abstractBo.getConcurrentUserName());
			temp.setBatchNumber(batchNubmer);
			temp.setCreateTime(now);
			
			
			
			String name = item0;
			String username = item1;
			// String duty = item2;
			String userTypeName = item3;
			String compName = item4;
			String roleName = item5;
			String sexName = item6;
			String ageName = item7;
			String phone = item8;
			
			if (name == null || "".equals(name.trim())) {
				temp.setReason(ExceptionCode.姓名为空.getMsg() + ": " + name);
				tempDao.insert(temp);
				tempList.add(temp);
				continue;
			}
			if (userTypeName == null || "".equals(userTypeName.trim())) {
				temp.setReason(ExceptionCode.入驻单位为空.getMsg() + ": " + userTypeName);
				tempDao.insert(temp);
				tempList.add(temp);
				continue;
			}
			if (compName == null || "".equals(compName.trim())) {
				temp.setReason(ExceptionCode.单位名称为空.getMsg() + ": " + compName);
				tempDao.insert(temp);
				tempList.add(temp);
				continue;
			}
			if (roleName == null || "".equals(roleName.trim())) {
				temp.setReason(ExceptionCode.角色为空.getMsg() + ": " + roleName);
				tempDao.insert(temp);
				tempList.add(temp);
				continue;
			}
			if (sexName == null || "".equals(sexName.trim())) {
				temp.setReason(ExceptionCode.性别为空.getMsg() + ": " + sexName);
				tempDao.insert(temp);
				tempList.add(temp);
				continue;
			}
			if (phone == null || "".equals(phone.trim())) {
				temp.setReason(ExceptionCode.电话为空.getMsg() + ": " + phone);
				tempDao.insert(temp);
				tempList.add(temp);
				continue;
			}
			
			try {
				if (ageName != null && !"".equals(ageName.trim())) {
					Integer.parseInt(ageName);
				}
			} catch (NumberFormatException e) {
				temp.setReason(ExceptionCode.年龄格式错误.getMsg() + ": " + ageName);
				tempDao.insert(temp);
				tempList.add(temp);
				continue;
			}
			
			
			
			
			Integer userType = userTypeMap.get(userTypeName);
			
			Company company = null;
			
			company = companyMap.get(compName);
			
			if (company == null) {
				temp.setReason(ExceptionCode.单位不存在.getMsg() + ": " + userTypeName + "-" + compName);
				tempDao.insert(temp);
				tempList.add(temp);
				continue;
			}
			Role role = roleMap.get(roleName);
			if (role == null) {
				temp.setReason(ExceptionCode.角色不存在.getMsg() + ": " + roleName);
				tempDao.insert(temp);
				tempList.add(temp);
				continue;
			}
			
			Long compId = company.getCompanyId();
			Long roleId = role.getRoleId();
			Integer sex = sexMap.get(sexName);
			Integer age = ageName != null && !"".equals(ageName.trim()) ? Integer.parseInt(ageName) : null;
			
			List<String> usernameList = new ArrayList<String>();
			if (username == null || "".equals(username.trim())) {
				usernameList.add(PingYinUtil.getFirstSpell(compName) + "-" + PingYinUtil.getFirstSpell(name));
				char ch = name.charAt(0);
				String family = String.valueOf(ch);
				String[] strList = name.split(family);
				String name2 = strList[1];
				usernameList.add(PingYinUtil.getFirstSpell(compName) + "-" + PingYinUtil.getFullSpell(family) + PingYinUtil.getFirstSpell(name2));
				usernameList.add(PingYinUtil.getFirstSpell(compName) + "-" + PingYinUtil.getFullSpell(name));
				
			}
			
			usernameFor:
			for (int j = 0; j < usernameList.size(); j++) {
				username = usernameList.get(j);
				List<User> existUserList = userRead.list(username);
				if (existUserList == null || existUserList.isEmpty()) {
					break usernameFor;
				}
				if (existUserList != null && !existUserList.isEmpty() && j == usernameList.size() - 1) {
					temp.setReason(ExceptionCode.账号已存在.getMsg() + ": " + username);
					temp.setItem1(username);
					tempDao.insert(temp);
	    			tempList.add(temp);
					continue outer;
				}
			}
			
			CreateUserBo param = new CreateUserBo();
			param.setName(name);
			param.setUsername(username);
			// param.setDuty(duty);
			param.setType(userType);
			param.setCompanyId(compId);;
			param.setRoleIdList(Arrays.asList(roleId));
			param.setSex(sex);
			param.setAge(age);
			param.setPhone(phone);
			
			Object result = userCreate.process(param);
			System.out.println(result);
			if (result instanceof ResponseSucc) {
				String reason = ((ResponseSucc) result).getMsg();
				temp.setReason(reason);
				tempDao.insert(temp);
				tempList.add(temp);
				continue;
			}
			temp.setReason(new ResponseSucc().getCode() + ":" + new ResponseSucc().getMsg());
			temp.setItem1(username);
			tempList.add(temp);
		}
		
		if (tempList.isEmpty()) {
			Temp t = new Temp();
			tempList.add(t);
		}
		
	    LinkedHashMap<String,String> map = ExcelUtil.getExportUserTempMap();
	    String fileName = System.currentTimeMillis() + ".xls";
	    response.setHeader("Content-disposition",
	            "attachment; filename=" + new String(fileName.getBytes("GB2312"), "utf-8"));
	    response.setContentType("application/msexcel");// 定义输出类型
	    OutputStream os = response.getOutputStream();
	    ExcelUtil.listToExcel(tempList, map, "导入流水表", os);
		
    	
        return null;
	}
	
			
}

